package hexagon.security.core.domain;

import com.avaje.ebean.Model;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * @author XueguiYuan
 * @version 1.0 (created time: 2016/12/3).
 */
@MappedSuperclass
public abstract class SecurityAbstractEntity extends Model {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public abstract String[] businessKeys();

    @Override
    public int hashCode() {
        HashCodeBuilder builder = new HashCodeBuilder(13, 37);
        for (String businessKey : businessKeys()) {
            try {
                builder = builder.append(BeanUtils.getProperty(this, businessKey));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return builder.toHashCode();
    }

    @Override
    public boolean equals(Object other) {
        if (this == other) {
            return true;
        }
        if (other == null) {
            return false;
        }
        if (businessKeys() == null || businessKeys().length == 0) {
            return false;
        }
        if (!(this.getClass().isAssignableFrom(other.getClass()))) {
            return false;
        }
        EqualsBuilder builder = new EqualsBuilder();
        for (String businessKey : businessKeys()) {
            try {
                builder.append(BeanUtils.getProperty(this, businessKey), BeanUtils.getProperty(other, businessKey));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return builder.isEquals();
    }
}
